package com.ywjt.platformbusiness.my.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.login.model.LoginModel;
import com.ywjt.platformbusiness.my.model.AddressModel;
import com.ywjt.platformbusiness.my.model.CitysBean;
import com.ywjt.platformbusiness.util.CitySelectUtils;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.SoftKeyboardUtils;
import com.ywjt.platformbusiness.util.StrUtils;
import com.ywjt.platformbusiness.widget.SwitchButton;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import static com.ywjt.platformbusiness.common.MethodUtils.getUserId;


public class ActivityAddAddress extends BaseActivity implements View.OnClickListener {
    private TextView tvAdd;
    private int from=0;
    private AddressModel.ResultDTO   addressmodel=null;
    private TextView tvAddressSelect;
    private SwitchButton switchbutton;
    private CitysBean citysBean1;
    private String address="";
    private TextView tvSave;
    private TextView tvDefault;
    //private ImageView ivSelect;
    private int status=0; //1默认  0未默认
    private EditText etName,etphone,etaddressDetail,etEmail;
    private String postalCode="",name="",phone="",detailAddress="";
   // private AddressDetail model;

    public static void actionStart(Context context, int from, AddressModel.ResultDTO model) {
        Intent intent = new Intent(context, ActivityAddAddress.class);
        intent.putExtra("from",from);
        intent.putExtra("model",(Serializable) model);
        context.startActivity(intent);
    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivityAddAddress.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tvAddressSelect:
                //三级联动地址选择器
                SoftKeyboardUtils.hideSoftKeyboard(this);
                citysBean1 = JSON.parseObject(StrUtils.getJson("startAddress.json", getContext()), CitysBean.class);
                CitySelectUtils citySelectUtils = new CitySelectUtils(getContext(), citysBean1);
                citySelectUtils.setCityCallBack(new CitySelectUtils.CityCallBack() {
                    @Override
                    public void city(String province, String city, String county) {
                        if (county.equals("全部")) {
                            address = province + " " + city;//如果区级是全部就给后台传省级/市级
                        } else {
                            address = province + " " + city + " " + county;//如果全有给后台传省级/市级/区级
                        }
                        tvAddressSelect.setText(address);
                    }

                    @Override
                    public void cancle() { }
                });
                break;
            case R.id.tvSave:
                //保存  在这里调用保存数据接口
                SoftKeyboardUtils.hideSoftKeyboard(this);
                if(from==1){
                    updateAddress();
                }else {
                    addAddress();
                }
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) { setAndroidNativeLightStatusBar(true); }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_add_address;
    }

    @Override
    protected void initView() {
        setTitleText("新建地址");
        addressmodel=(AddressModel.ResultDTO) getIntent().getSerializableExtra("model");
        from=getIntent().getIntExtra("from",0);
        switchbutton=findViewById(R.id.switchbutton);
        switchbutton.setOnCheckedChangeListener(listener);
        etEmail=findViewById(R.id.etEmail);
        tvSave=findViewById(R.id.tvSave);
        etName=findViewById(R.id.etName);
        etphone=findViewById(R.id.etphone);
        tvAddressSelect=findViewById(R.id.tvAddressSelect);
        etaddressDetail=findViewById(R.id.etaddressDetail);
        if(from==1){//编辑收货地址
            setTitleText("编辑收货地址");
           if (addressmodel!=null){
               setView();
           }
        }else {
            setTitleText("新增收货地址");
        }

        etEmail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                postalCode=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                name=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                phone=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etaddressDetail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                detailAddress=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tvAddressSelect.setOnClickListener(this);
        tvSave.setOnClickListener(this::onClick);
    }

    //Switchbutton监听事件
    SwitchButton.OnCheckedChangeListener listener=new SwitchButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(SwitchButton view, boolean isChecked) {
            if(isChecked){
                status=1;
            }else {
                status=0;
            }
        }
    };

    //添加地址
    public void addAddress(){
        Map map = new HashMap();

            map.put("userId", getUserId(getContext()));
            map.put("name",name);
            map.put("detailAddress",detailAddress);
            map.put("phone",phone);
            map.put("address",address);
            map.put("postalCode",postalCode);//邮政编码
            map.put("isDefault",String.valueOf(status));//是否默认


        new HttpRequest(getContext()).doGet(UrlConstants.merchant_insertNewAddress, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    //修改地址update
    public void updateAddress(){
        Map map = new HashMap<>();

            map.put("userId", getUserId(getContext()));
            map.put("id",String.valueOf(addressmodel.getId()));
            if (!name.equals("")){
                map.put("name",name);
            }

            if (!phone.equals("")){
                map.put("phone",phone);
            }
            if (!detailAddress.equals("")){
                map.put("detailAddress",detailAddress);
            }
            map.put("isDefault",String.valueOf(status));//是否默认

            if (!postalCode.equals("")){
                map.put("postalCode",postalCode);//邮政编码
            }
            if (!address.equals("")){
                map.put("address",address);
            }

        new HttpRequest(getContext()).doGet(UrlConstants.merchant_updateAddress, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                        if (obj instanceof BaseModel) {
                            BaseModel model = (BaseModel) obj;
                            finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    public void setView(){
        etaddressDetail.setText(addressmodel.getDetailAddress());
        etName.setText(addressmodel.getName());
        etphone.setText(addressmodel.getPhone());
        tvAddressSelect.setText(addressmodel.getAddress());
        etaddressDetail.setText(addressmodel.getDetailAddress());
        etEmail.setText(addressmodel.getPostalCode());
        if(addressmodel.getIsDefault()==1){//1 默认 0 不是默认
            switchbutton.setChecked(true);
        }else {
            switchbutton.setChecked(false);
        }
    }

    @Override
    protected void initData() {
    }

    @Override
    protected int getTitleBarType() {
        return 0;
    }
}